<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="电话" prop="phoneNumber">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:region:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:region:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:region:del']">批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" max-height="650px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="归属区域" align="center" :show-overflow-tooltip="true" prop="regionName" width="120" />
      <el-table-column label="归属门店" align="center" prop="storeName" />
      <!-- <el-table-column label="归属区域id" align="center" prop="belongAreaIds" /> -->
      <!-- <el-table-column label="归属区域名称" align="center" prop="belongAreaNames" /> -->
      <el-table-column label="头像封面" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" :show-overflow-tooltip="true" prop="userName" />
      <el-table-column label="电话" align="center" prop="phoneNumber" />
      <el-table-column label="性别" align="center" prop="gender" >
      <template slot-scope="scope">
         <div>
          {{ gender[scope.row.gender].value }}
         </div>
        </template>
      </el-table-column>
      <el-table-column label="岗位" align="center" prop="postName">
        <template slot-scope="scope">
          <span>{{ scope.row.postName ? scope.row.postName : '暂无' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色" align="center" prop="roleName">
        <template slot-scope="scope">
          <span>{{ scope.row.roleName ? scope.row.roleName : '暂无' }}</span>
        </template>
      </el-table-column>

    
    
      <el-table-column label="状态" align="center" prop="onTheJob">
        <template slot-scope="scope">
          <span>{{ scope.row.onTheJob == '1' ? '在职' : '离职' }}</span>
        </template>
      </el-table-column>



      
      <el-table-column label="视力情况" align="center" prop="eyesight" >
      <template slot-scope="scope">
         <div>
          {{ eyesight[scope.row.eyesight].value }}
         </div>
        </template>
      </el-table-column>
      <el-table-column label="身份证正面" align="center" prop="identificationCardFront" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.identificationCardFront" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="身份证背面" align="center" prop="identificationCardBack" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.identificationCardBack" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="dateOfBirth" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateOfBirth, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    
      <!-- <el-table-column label="归属门店id" align="center" prop="belongStoreIds" /> -->
    
      <el-table-column label="入职类型" align="center" prop="entryType" >
      <template slot-scope="scope">
        <div>{{ scope.row.entryType ==1?'全职':'兼职'}}</div>
        </template>
      </el-table-column>
      <el-table-column label="通讯地址" :show-overflow-tooltip="true" align="center" prop="address" />
      <el-table-column label="合同" align="center" prop="contract" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.contract" :width="50" :height="50" />
        </template>
      </el-table-column>
      
      <el-table-column label="创建人"   align="center"  prop="createBy" />
      <el-table-column label="创建时间"   align="center"  prop="createTime" />
      <el-table-column label="修改人"   align="center"  prop="updateBy" />
      <el-table-column label="修改时间"   align="center"  prop="updateTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:region:edit']">修改</el-button>

          <el-button size="mini" type="text"
          v-hasPermi="['business:region:editpass']"
           icon="el-icon-edit" @click="updatePassword(scope.row)">修改密码</el-button>

          <!-- <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleGround(scope.row,status=1)"
            v-hasPermi="['system:technology:edit']" :disabled="scope.row.status===1">在职</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-download" 
          v-hasPermi="['business:region:dimission']"
          @click="handleGround(scope.row, 0)"
            :disabled="scope.row.onTheJob === '0'">离职</el-button>


          <el-button size="mini" type="text" icon="el-icon-download"
          v-hasPermi="['business:region:entry']" @click="handleGround(scope.row, 1)"
            :disabled="scope.row.onTheJob != '0'">入职</el-button>

          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:region:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postId" placeholder="请选择岗位" @change='changePost'>
                <el-option v-for="item in postOptions" :key="item.value" :label="item.label" :value="item.value"
                  :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限角色">
              <el-select v-model="form.roleId" placeholder="请选择权限角色">
                <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value">{{
                  item.label }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入姓名" style="width: 222px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入电话" style="width: 222px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="区域" prop="regionId">
              <el-select clearable v-model="form.regionId" @change='changeRegion'>
                <el-option v-for="(item, index) of region" :key="item.key" :label="item.value" :value="item.key">
                  {{ item.value }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="this.postId == 3">
            <el-form-item label="适用门店" prop="storeId">
              <el-select clearable v-model="form.storeId" @change='changeStore'>
                <el-option v-for="(item, index) of store" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="onTheJob">
              <el-select clearable v-model="form.onTheJob">
                <el-option v-for="(item, index) of List" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="视力情况" prop="eyesight">
              <el-select clearable v-model="form.eyesight">
                <el-option v-for="(item, index) of eyesight" :key="index" :label="item.value" :value="item.key">{{
                  item.value }}</el-option>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select clearable v-model="form.gender">
                <el-option v-for="(item, index) of gender" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="入职类型" prop="entryType">
              <el-select clearable v-model="form.entryType">
                <el-option v-for="(item, index) of entryType" :key="index" :label="item.value" :value="item.key">{{
                  item.value }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="出生日期" prop="dateOfBirth">
              <el-date-picker clearable v-model="form.dateOfBirth" :picker-options="pickerOptions" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择出生日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- <el-row>

          <el-col :span="12">
            <el-form-item label="归属区域" prop="regionIds">
              <el-input v-model="form.regionIds" placeholder="请输入归属区域" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="归属门店" prop="belongStoreIds">
              <el-input v-model="form.belongStoreIds" placeholder="请输入归属门店" />
            </el-form-item>
          </el-col>

        </el-row> -->

        <el-row>
          <el-col :span="12">
            <el-form-item label="底薪" prop="basicSalary">
              <el-input v-model="form.basicSalary"
              
              @input="
            (value) => (this.form.basicSalary = value.replace(/[^\d]/g, ''))
          "
              placeholder="请输入底薪" style="width: 222px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯地址" prop="address">
              <el-input type="textarea" v-model="form.address" placeholder="请输入通讯地址" style="width: 222px;" />
            </el-form-item>
          </el-col>
        </el-row>



        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证正面" prop="identificationCardFront">
              <image-upload v-model="form.identificationCardFront" :limit="1" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="身份证背面" prop="identificationCardBack">
              <image-upload v-model="form.identificationCardBack"  :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同" prop="contract">
              <image-upload v-model="form.contract" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="头像封面" prop="avatar">
              <image-upload v-model="form.avatar"  />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码 -->
    <el-dialog title="用户信息" :visible.sync="isUpdatePassword">
      <el-form ref="form2" :model="userInfo" label-width="120px">
        <el-form-item label="用户名">
          <div>{{ userInfo.userName }}</div>
        </el-form-item>
        <el-form-item label="登录账号">
          <div>{{ userInfo.phoneNumber }}</div>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="userInfo.password" maxlength="6" minlength="6"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateUserPassword">确 定</el-button>
        <el-button @click="isUpdatePassword = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { listmanager, getItemProduct, delitemProduct, addItemManager, updateitemProduct, listMemberRegion, listMemberStore, regionList, roleList } from "@/api/system/personnel/region";
import { listRole } from "@/api/system/role";
import { resetUserPwd } from "@/api/system/user";

export default {
  name: "Store",
  data() {
    return {
      pickerOptions: {
        disabledDate(v) {
          return v.getTime() > new Date().getTime() - 86400000;//  - 86400000是否包括当天
        }
      },

      map: null,
      local: null,
      mk: null,
      latitude: '',
      longitude: '',
      keyWords: '',
      result: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        storeName: null,
        storeName: null,
        userName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        onTheJob: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        regionId: [
          { required: true, message: '请选择所属区域', trigger: 'blur' },
        ],
        userName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1到 10 个字符', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ],
        onTheJob: [
          { required: true, message: '请选择所属区域', trigger: 'blur' },
        ],
        storeId: [
          { required: true, message: '请选择适用门店', trigger: 'blur' }
        ]
      },
      options: [],
      List: [
        {
          key: '1',
          value: '在职'
        },
        {
          key: '0',
          value: '离职'
        },
      ],
      gender: [
        {
          key: 0,
          value: "男",
        },
        {
          key: 1,
          value: "女",
        },
        {
          key: 2,
          value: "未知",
        },
      ],
      //视力情况
      eyesight: [
        {
          key: 0,
          value: "正常",
        },
        {
          key: 1,
          value: "半盲",
        },
        {
          key: 2,
          value: "全盲",
        },
      ],
      //入职类型
      entryType: [
        {
          key: 1,
          value: "全职",
        },
        {
          key: 2,
          value: "兼职",
        },
      ],
      region: [],
      store: [],
      // 岗位选项
      postOptions: [
        { label: '大区经理', value: 1 },
        { label: '部门经理', value: 2 },
        { label: '门店管理员', value: 3 },
        { label: '区域管理员', value: 4 },
      ],
      // 角色选项
      roleOptions: [],
      postIds: [],
      roleIds: [],
      postId: null,
      isUpdatePassword: false,
      userInfo: {
        // 修改密码
        phoneNumber:'',
        password: '',
        userId: ''
      },
    };
  },
  watch: {
    'form.postId': {
      handler: function (newVal) {
        if (newVal) {
          const id = newVal
          this.$nextTick(() => {
            if (id == 3) {
              listMemberRegion(id).then((res) => {
                this.region = res.data.map((rItem) => {
                  return {
                    key: rItem.id,
                    value: rItem.regionName,
                  };
                });
              });
            } else if (id == 4) {
              regionList(id).then((res) => {
                this.region = res.data.map((rItem) => {
                  return {

                    key: rItem.regionId,
                    // value: rItem.bigRegionName,
                    value: rItem.regionName,
                  };
                });
              });
            } else {
              regionList(id).then((res) => {
                this.region = res.data.map((rItem) => {
                  return {
                    key: rItem.id,
                    value: rItem.bigRegionName,
                  };
                });
              });
            }
          });
        }
      }
    },
  },
  created() {
    this.getList();
    console.log(this.$store.state);
    this.getRoleList()
  },
  methods: {
    // listregion(){
    //   const id = this.postId
    //   regionList(id).then(res=>{
    //       this.region = res.data.map(rItem => {
    //         return {
    //           key: rItem.id,
    //           value: rItem.regionName,
    //         }
    //     })
    //   })
    // },

    updatePassword(row) {
      this.userInfo.userName = row.userName
      this.userInfo.userId = row.userId
      this.userInfo.phoneNumber = row.phoneNumber
      
      this.userInfo.password = ''
      this.isUpdatePassword = true;

    },
    updateUserPassword() {
      let rules =   /^[a-zA-Z0-9]{6,16}$/;
      if (rules.test(this.userInfo.password)) {
        resetUserPwd(this.userInfo.userId, this.userInfo.password).then(res => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "修改成功,密码为：" + this.userInfo.password,
            });
            this.isUpdatePassword = false;
            this.getList();
          }

        })
      } else {
        this.$message({
          type: "info",
          message: "请输入数字或者字母的6位数密码",
        });
      }

    },
    //岗位的change事件
    changePost(value) {
      this.postId = value
      let item = this.postOptions.find(item => item.value == value)
      if (item) this.form.postName = item.label
      // this.listregion()
    },
    //区域的change事件
    changeRegion(value) {
      console.log(value, 'value888')
      const selectedOption = this.region.find(item => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      console.log(`Selected Key: ${selectedKey}`);
      console.log(`Selected Value: ${selectedValue}`);
      this.form.regionName = selectedValue
      listMemberStore({ regionId: value }).then(res => {
        this.store = res.data.map(rItem => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          }
        })
      })
    },
    getStore(value) {
      listMemberStore({ regionId: value }).then(res => {
        this.store = res.data.map(rItem => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          }
        })
      })
    },
    changeStore(value) {
      console.log(value, this.store)
      const selectedOption = this.store.find(item => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      console.log(`Selected Key: ${selectedKey}`);
      console.log(`Selected Value: ${selectedValue}`);
      this.form.storeName = selectedValue
      console.log(this.form.storeName, 555);
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listmanager(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        onTheJob: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
        gender: null,
        eyesight: null,
        identificationCardFront: null,
        basicSalary: null,
        identificationCardBack: null,
        dateOfBirth: null,
        avatar: null,
        belongStoreIds: null,
        belongStoreNames: null,
        belongAreaIds: null,
        belongAreaNames: null,
        entryType: null,
        address: null,
        contract: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加区域管理员";
    },
    // 获取角色权限列表
    getRoleList() {
      roleList().then(response => {
        this.roleOptions = response.data.filter(item =>!(item.roleId == 1 || item.roleName =='技师')).map((item) => {
          return {
            label: item.roleName,
            value: item.roleId
          }
        });
      });
    },
    // 上下架
    handleGround(row, onTheJob) {
      const params = {
        id: row.id,
        onTheJob: onTheJob
      }
      this.$confirm(`确定要 ${onTheJob === 1 ? '入职' : '离职'} 吗 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateitemProduct(params).then((res) => {
          this.$message({
            type: 'success',
            message: `${onTheJob === 1 ? '入职' : '离职'}成功!`
          });
          this.getList()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getItemProduct(id).then(response => {
        // this.form = response.data;
        console.log(response.data, 'response.data')
        this.form = response.data
        this.postId = response.data.postId
        // this.form.regionId = response.data.regionId.join(',').map((item) => Number(item))
        this.open = true;
        console.log(this.form)
        this.title = "修改区域管理员";
        this.getStore(this.form.regionId)
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const params = {
            ...this.form,
          }
          if (this.form.id != null) {
            updateitemProduct(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItemManager(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handReset(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认重置编号为"' + ids + '"的数据项？').then(function () {
        return listResetPwd({ userId: ids });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("重置成功");
      }).catch(() => { });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return delitemProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.dialog-footer {
  text-align: center;
}
</style>
